package org.gthelper.imageProcess;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.media.jai.remote.SerializableRenderedImage;

import org.apache.hadoop.io.Text;
//import org.geotools.coverage.GridSampleDimension;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.gce.geotiff.GeoTiffReader;
import org.geotools.gce.geotiff.GeoTiffWriter;
import org.gthelper.hdpWritable.HdpRenderedImageWritable;
import org.opengis.geometry.Envelope;
import org.opengis.parameter.GeneralParameterValue;

import com.sun.media.jai.codecimpl.util.RasterFactory;

/**
 * 用于上传下载的geotiff切分、拼合与还原
 * @author 陈宁
 */
public class geotiffTreater {

	static {
        System.setProperty("com.sun.media.jai.disableMediaLib", "true");
    }
	
	/**
	 * 读取geotiff文件并获得geotiff
	 * @param filepath geotiif文件路径
	 * @return GridCoverage2D对象
	 * @throws Exception
	 */
	public static GridCoverage2D read(String filepath) throws Exception
	{
		GeoTiffReader tiffReader = new GeoTiffReader(new File(filepath));		
		GridCoverage2D tiffGC = (GridCoverage2D) tiffReader.read(null);				
		return tiffGC;
	}
	
	
	/**
	 * @param RenderedImage
	 * @param splitpixelsize
	 * @param residulepixelsize
	 * @return ArrayList<HdpRenderedImageWritable>
	 * 
	 * 切分函数，输入一张图片，给定切分大小和冗余大小，做切分
	 */
	public ArrayList<HdpRenderedImageWritable> split(RenderedImage sourceImage,int splitpixelsize ,int residulepixelsize,String filename)
	{
		ArrayList<HdpRenderedImageWritable> resultlist = new ArrayList<HdpRenderedImageWritable>();
		WritableRaster sourceRaster = (WritableRaster)sourceImage.getData();
		ColorModel sourcecColorModel = sourceImage.getColorModel();
		BufferedImage resultBufferedImage = new BufferedImage(sourcecColorModel, sourceRaster, false, null);
		int pixelsize_x = resultBufferedImage.getWidth();
		int pixelsize_y = resultBufferedImage.getHeight();
		for(int rawpostion_x=0,i=0;rawpostion_x<pixelsize_x-1;rawpostion_x+=splitpixelsize,i++)
		{
			for(int rawpostion_y=0,j=0;rawpostion_y<pixelsize_y-1;rawpostion_y+=splitpixelsize,j++)
			{
				int startposition_x=0,startposition_y=0,endposition_x=0,endposition_y=0;
				startposition_x=rawpostion_x-residulepixelsize;
				if(startposition_x<0) startposition_x=0;
				startposition_y = rawpostion_y-residulepixelsize;
				if(startposition_y<0) startposition_y=0;
				endposition_x=rawpostion_x+splitpixelsize +residulepixelsize-1;
				if(endposition_x>pixelsize_x-1) endposition_x=pixelsize_x-1;
				endposition_y = rawpostion_y+splitpixelsize +residulepixelsize-1;
				if(endposition_y>pixelsize_y) endposition_y=pixelsize_y-1;
				int splitwidth = endposition_x-startposition_x+1;
				int splitheight = endposition_y-startposition_y+1;
				
				BufferedImage splitBufferedImage = resultBufferedImage.getSubimage(startposition_x, startposition_y, splitwidth, splitheight);
				HdpRenderedImageWritable splitHdpRenderedImageWritable = new HdpRenderedImageWritable();
				splitHdpRenderedImageWritable.set(new Text(filename),i,j, startposition_x, startposition_y,new SerializableRenderedImage(splitBufferedImage,true));
				resultlist.add(splitHdpRenderedImageWritable);
//				System.out.println("start_X="+startposition_x+" start_y="+startposition_y+" end_x="+endposition_x+" end_y="+endposition_y+"type="+splitBufferedImage.getType());
			}
		}
		return resultlist;
	}
	
	/**
	 * 拼合小图像，获得大图的对象
	 * @param sourcelist
	 * @param pixelsize_x 大图的宽度（像素）
	 * @param pixelsize_y 大图的高度（像素）
	 * @return
	 */
	public RenderedImage imagejoint(ArrayList<HdpRenderedImageWritable> sourcelist,int pixelsize_x,int pixelsize_y)
	{
		RenderedImage splitsample = sourcelist.get(0).sri;
		ColorModel colorModel = splitsample.getColorModel();
		int bandnum = splitsample.getSampleModel().getNumBands();
		int databuffertype = splitsample.getData().getDataBuffer().getDataType();
		WritableRaster raster = RasterFactory.createBandedRaster(databuffertype,pixelsize_x,pixelsize_y,bandnum,null);
		//BufferedImage resultBufferedImage = new BufferedImage(colorModel, raster, false, null);
		for(int i=0;i<sourcelist.size();i++)
		{
			
			HdpRenderedImageWritable splitimage = sourcelist.get(i);
			Raster splitRaster = splitimage.sri.getData();
//			System.out.println(splitimage.position_x+" "+splitimage.position_y);
			int startposition_x = splitimage.position_x;
			int startposition_y = splitimage.position_y;
			int splitwidth = splitimage.sri.getWidth();
			int splitheight = splitimage.sri.getHeight();
			for(int w=0;w<splitwidth;w++)
			{
				for(int h=0;h<splitheight;h++)
				{
					for(int b=0;b<bandnum;b++)
					{
						raster.setSample(startposition_x+w, startposition_y+h,b,splitRaster.getSampleDouble(w, h, b));
					}
				}
			}
			
		}
		BufferedImage resultBufferedImage = new BufferedImage(colorModel, raster, false, null);
		return resultBufferedImage;
	}
	
	/**
	 * 由RenderedImage生成GridCoverage2D以还原geotiff
	 * @param sourceimage
	 * @param env
	 * @param bands
	 * @return
	 */
	public GridCoverage2D creategeotifffromrenderimage(String str,RenderedImage sourceimage,Envelope env)
	{
		GridCoverageFactory gf = new GridCoverageFactory();
	    GridCoverage2D newCov = gf.create(str, sourceimage, env);
		return newCov;
	}
	
	/**
	 * 保存geotiff到磁盘
	 * @param tifGc
	 * @param path
	 * @param gpv
	 * @throws IOException
	 */
	public void saveGeotiff(GridCoverage2D tifGc,String path,GeneralParameterValue[] gpv) throws IOException
	{
		GeoTiffWriter writer = new GeoTiffWriter(new File(path));
		writer.write(tifGc, gpv);
		writer.dispose();
	}
	
}
